import {
  Injectable,
  Body,
  UseInterceptors,
  ClassSerializerInterceptor,
} from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { InjectEntityManager, InjectRepository } from '@nestjs/typeorm';
import { User } from './entities/user.entity';
import { Tag } from 'src/tag/entities/tag.entity';

@Injectable()
export class UserService {
  @InjectRepository(User)
  private readonly userRepository;

  @InjectEntityManager()
  private readonly entityManager;

  async create(createUserDto: CreateUserDto) {
    const tags = createUserDto.tags || [];
    const tagTargetList = [];
    if (Object.keys(tags).length != 0) {
      for (let i = 0; i < tags.length; i++) {
        const listOne = await this.entityManager.findOne(Tag, {
          where: {
            id: tags[i],
          },
        });
        tagTargetList.push(listOne);
      }
    }
    createUserDto.tags = tagTargetList;
    console.log('===============createUserDto=========');
    console.log(createUserDto);
    const res = await this.userRepository.save(createUserDto);
    return res;
    return 'This action adds a new user' + JSON.stringify(createUserDto);
  }
  async findAll() {
    const user = await this.userRepository
      .createQueryBuilder('user')
      .leftJoinAndSelect('user.idCard', 'idCard')
      // .leftJoinAndSelect('user.jobIds', 'jobIds')
      .leftJoinAndSelect('user.tags', 'tags')

      // .where('user.id = :id', { id: 2 })
      // .select(['user', 'idCard.value AS idCardValue'])
      // .addSelect('idCard.value', 'idCardValue')
      // .addSelect('idCard.id', 'idCardId')
      .getMany();
    return user;
  }

  findOne(id: number) {
    return `This action returns a #${id} user`;
  }

  async findUserByEmail(email: string) {
    const user = await this.userRepository.findOne({ where: { email } });
    return user;
  }

  update(id: number, updateUserDto: UpdateUserDto) {
    return `This action updates a #${id} user`;
  }

  remove(id: number) {
    return `This action removes a #${id} user`;
  }

  findByUsername(username: string) {
    return this.userRepository.findOne({ where: { username } });
  }

  async fn1() {
    const a1 = new User();
    a1.name = 'aaaa';
    a1.desc = 'aaaaaaaaaa';

    const a2 = new User();
    a2.name = 'bbbbbb';
    a2.desc = 'bbbbbbbbbb';

    const t1 = new Tag();
    t1.name = 'ttt1111';
    t1.desc = 'ttt1111--desc';

    const t2 = new Tag();
    t2.name = 'ttt2222';
    t2.desc = 'ttt222--desc';

    const t3 = new Tag();
    t3.name = 'ttt33333';
    t3.desc = 'ttt3333--desc';

    a1.tags = [t1, t2];
    a2.tags = [t1, t2, t3];

    const entityManager = this.entityManager;

    await entityManager.save(t1);
    await entityManager.save(t2);
    await entityManager.save(t3);

    await entityManager.save(a1);
    await entityManager.save(a2);
  }
}
